<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>把韵味杭州带在身边</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
     <meta name="apple-touch-fullscreen" content="YES">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
    <!--<link rel="stylesheet" type="text/css" href="//cdn.bootcss.com/animate.css/3.5.2/animate.min.css">-->
    <!-- <link rel="stylesheet" type="text/css" href="/Public/projects/card/libs/animate.css"> -->
    <link rel="stylesheet" type="text/css" href="/Public/projects/card/style/base.css">
    <link rel="stylesheet" type="text/css" href="/Public/projects/card/style/index.css?v=5">
    <!-- <link rel="stylesheet/less" type="text/css" href="/Public/projects/card/style/index.less"> -->
</head>
<body>
<div class="share container none">
    <div class="bg" onclick="">
        <img src="/Public/projects/card/assets/images/share.png">
    </div>
</div>
<div class="container mobile">
    <div class="bg">
        <audio id="bgm" src="/Public/projects/card/assets/bgm/bgm.mp3" loop="loop">
            您的浏览器不支持 audio 标签。
        </audio>
        <div class="bgm ico button"></div>
        <img src="/Public/projects/card/assets/images/p2_bg.png">
        <div class="mobile-wrapper h-center">
            <img src="/Public/projects/card/assets/images/base_mobile.png">
            <div class="img-wrapper">
                <img id="mobile" class="" src="/Public/projects/card/assets/images/btn_upload.png" alt="无图片">
                <div class="uploader btn h-center v-center">
                    <input type="file" id="uploader">
                </div>
            </div>
            <div class="input-wrapper">
                <textarea rows="2" id="txt-input">{$reg['content']}</textarea>
                <div class="placeholder"></div>
            </div>
        </div>
        <div class="bottom">
            <?php if((I('get.share','','') != 1) && (empty($reg) || I('get.self','','') == 1)){ ?>
            <div class="button btn-confirm"></div>
            <div class="button btn-share"></div>
            <?php }else{?>
            <div class="button btn-make"></div>
            <?php }?>
        </div>
    </div>

    <div class="mask none" id="dialog">
        <div class="info-dialog h-center">
            <input type="text" id="name">
            <input type="text" id="phone">
            <p class="submit-tips none h-center">正在提交，请稍后...</p>
            <div class="buttons h-center">
                <div class="button btn-submit"></div>
                <div class="button btn-back close"></div>
            </div>
        </div>
    </div>

</div>

<!-- ========================================================================= -->
<script src="/Public/projects/card/libs/jquery-3.1.1.min.js"></script>
<!-- <script src="/Public/projects/card/libs/less.js"></script> -->
<!--common of all js file-->
<script src="/Public/projects/card/js/common.js?v=1"></script>

<script type="text/javascript" src="/Public/projects/card/libs/exif.js"></script>
<!--add self scrip file-->
<script>
    $(function () {
        var bgm = ns.getLocationParams()["bgm"] || 1;
        bgm = Number(bgm);
        $(".container.share").tap(function(){
            $(this).addClass("none");
            $(".container.mobile").removeClass("none");
        });
        if("{$reg['content']}" != ''){
            $("#txt-input").siblings(".placeholder").hide();
        }
        $("#txt-input")
            .focus(function () {
                $(this).siblings(".placeholder").hide();
            })
            .blur(function () {
                var $input = $(this);
                if($input.val().length == 0){
                    $input.siblings(".placeholder").show();
                }
            });

        setCompressedImage("<?php if(empty($reg) || empty($reg['picurl'])){\
                echo '/Public/projects/card/assets/images/img_mobile.png';\
            }else{\
                echo $reg['picurl'];\
            } ?>");

        function setCompressedImage(url){
            var image = new Image();
            image.onload = function () {
                EXIF.getData(this, function() {
                    var make = EXIF.getTag(this, "Make"),
                        model = EXIF.getTag(this, "Model"),
                        orientation = EXIF.getTag(this, 'Orientation');
                    // alert("orientation = " + orientation);
                    var $mobile = $("#mobile");
                    var isRotation = false;
                    if(orientation == 6){
                        isRotation = true;
                        $mobile.addClass("rotate");
                    }
                    var data = compress(image,img.type ,512,1024,isRotation);    //图片首先进行压缩
                    $mobile.attr("src", data.src);
                    $mobile.attr("result",data.org);
                });

            }
            image.src = url;
        }

        function uploadImg(event) {
            var img = event.target.files[0];
            // 判断是否图片
            if(!img) return ;
            // 判断图片格式
            if(!(img.type.indexOf('image')==0 && img.type && (/\.jpg$|\.png$|\.jpeg$|\.gif$/i).test(img.name)) ){
                alert('图片只能是jpg,png');
                return ;
            }
            var reader = new FileReader();
            reader.readAsDataURL(img);
            $("#mobile").removeClass("rotate");
            reader.onload = function (e) {
                var result = e.target.result;
                var maxSize = 1024 * 1024;// 大于1M 的图片 进行压缩
                if(result.length < maxSize) {
                    $("#mobile").attr("src", result);
                    $("#mobile").attr("result",result);
                } else {
                    setCompressedImage(result);
                }
            } ;
        }

        $("#uploader").on("change",function (event) {
            uploadImg(event);
        });

        function resizeWindow(){
            var $body = $("body");
            var w = $body.width();
            var h = $body.height();

            if(h / w < 1.6){
                $("html,body").css({"overflow-y": "visible"});
            }else{
                $("html,body").css({"overflow-y": "hidden"});
            }
        }

        resizeWindow();

        window.addEventListener("resize", resizeWindow, false);

        var
                canvas = document.createElement('canvas'),
                ctx = canvas.getContext('2d');

        function resize(img ,size) {
            var w,h,s,x=0,y=0;
            if(img.width>img.height){
                s = img.height / size.h;
                h = img.height;
                x = (img.width - size.w*s) / 2;
                w = img.width - x*2;
            }else{
                s = img.width / size.w;
                w = img.width;
                y = (img.height - size.h*s) / 2;
                h = img.height - y*2;
            }
            return{
                x:x ,y:y, w:w, h:h
            }
        }

        function compress(img ,type, srcSize ,uploadSize,isRotation) {
            var data = {};

            var size = {"w":srcSize*1.07 ,"h":srcSize};
            var rect = resize(img ,size);
            canvas.width = size.w;
            canvas.height = size.h;
            ctx.drawImage(img, rect.x, rect.y, rect.w, rect.h,0, 0,size.w,size.h);
            data.src = canvas.toDataURL(type||'image/jpeg', 1);
            var ch ,cw;
            if(img.height < img.width){
                ch = uploadSize;
                cw = img.width * ch/img.height;
            }else{
                cw = uploadSize;
                ch = img.height * cw/img.width;
            }
            
            if(isRotation){
                var temp = ch;
                ch = cw;
                cw = temp;
                canvas.width = cw;
                canvas.height = ch;
                //保存状态
                ctx.save();
                // 设置画布原点到中点
                ctx.translate(cw/2,ch/2);
                //逆时针旋转90度
                ctx.rotate(90*Math.PI/180); 
                //再设置到画布原点，注：旋转后画布的宽高 = 原先的高宽！
                ctx.translate(-ch/2,-cw/2); 
                //参数： 图像 ，图原点x,图原点y ,图源的宽，图源的高，画布原点x，画布原点y，画布宽（旋转后值变成了以前的高） ，画布高（旋转后值变成了以前的宽）
                ctx.drawImage(img, 0,0,img.width,img.height, 0, 0,ch,cw);
                //恢复状态
                ctx.restore();

            }else{
                canvas.width = cw;
                canvas.height = ch;
                ctx.drawImage(img, 0,0,img.width,img.height, 0, 0,cw,ch);
            }

            data.org = canvas.toDataURL(type||'image/jpeg', 1);

            return data;
        }

        $(".btn-share").tap(function () {
            //ns.navigate( ns.route("share.html")+"?id="+ns.getId() +"&bgm="+bgm);
            $(".container.share").removeClass("none");
            $(".container.mobile").addClass("none");
        });

        $(".btn-confirm").tap(function () {
            if($.isEmptyObject( $("#mobile").attr("src") )){
                alert("您好，请上传图片!");
            }else{
                $("#dialog").show();
            }
        });

        $("#dialog").tap(function () {
            $(this).hide();
        });
        $(".info-dialog").tap(function (e) {
            e.stopPropagation();
        });
        $(".button.close").tap(function () {
            $("#dialog").hide();
        });

        $(".btn-submit").tap(function () {

            var
                    name = $("#name").val()
                    ,mobile = $("#phone").val()
                    ,pic = $("#mobile").attr("result")
                    ,content = $("#txt-input").val()
            ;
            var boo = false ,msg = "";
            do{
                if($.isEmptyObject(name)){
                    msg = "您好，请填写姓名!";
                    break;
                }
                if(!ns.verify("mobile", mobile)){
                    msg = "您好，请填写正确的号码!";
                    break;
                }
                boo = true;
            }while(false);
            if(!boo){
                alert(msg);
                return;
            }
            $(".submit-tips").css("color","#2c7c7c");
            $(".submit-tips").text("正在上传，请稍后...").show();
            $(".buttons").hide();
            ns.ajax({
                type:"post",
                url:"register",
                data:{
                    id: ns.getId(),
                    name: name,
                    mobile:mobile,
                    pic:pic,
                    content:content
                }
                ,success:function (result) {
                    if(result.status == 1){
                        $(".submit-tips").text("上传成功!");
                        window.location = "/Wap/Card/mobile?id={$card['card_id']}&self=1&bgm=" + bgm + "&reg_id=" + result.result;
                    }else{
                        $(".submit-tips").text(result.result);
                        $(".submit-tips").css("color","red");
                    }
                    setTimeout(function(){
                        $("#dialog").hide();
                        $(".submit-tips").hide();
                        $(".buttons").show();
                    },2000);                   
                    
                }
            })
        });

        function toggleBgm ($bgm ,boo){
            if(boo){
                $bgm.addClass("on");
                $bgm.addClass("animated");
                $bgm.addClass("anim-rotate");
                $("#bgm")[0].play();
                bgm = 1;
            }else{
                $bgm.removeClass("on");
                $bgm.removeClass("animated");
                $bgm.removeClass("anim-rotate");
                $("#bgm")[0].pause();
                bgm = 0;
            }
        }


        if(bgm>0){
            setTimeout(function(){
                toggleBgm($(".button.bgm"), true);
            },500);
            if(wx){
                document.addEventListener("WeixinJSBridgeReady", function () {
                    setTimeout(function(){
                        toggleBgm($(".button.bgm"),true);
                    },500);
                }, false);
            }
        }

        $(".button.bgm").tap(function () {
            toggleBgm($(this) , ! $(this).hasClass("on"));
        });
        $(".btn-make").click(function(){
            window.location = "/Wap/card/index?id={$card['card_id']}&bgm=" + bgm;
        });
        
    });

</script>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">
    var img = location.protocol + "//" + window.location.hostname + "{$card['share_pic']}";
    if("{$reg['picurl']}" != ""){
        img = location.protocol + "//" + window.location.hostname + "{$reg['picurl']}";
    }
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: '{$wxuser["appid"]}', // 必填，公众号的唯一标识
        timestamp: "{$timestamp}", // 必填，生成签名的时间戳
        nonceStr: '{$nonceStr}', // 必填，生成签名的随机串
        signature: '{$wxSha1}',// 必填，签名，见附录1
        jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });
    wx.error(function(res){
        //console.log(res);
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
    });
    wx.ready( function( e ){
        wx.onMenuShareAppMessage({
            title: "{$card['share_title']}", // 分享标题
            desc: "{$card['share_desc']}", // 分享描述
            link: location.protocol + "//" + window.location.hostname + "/Wap/Card/mobile?id={$card['card_id']}&reg_id={$reg['reg_id']}&share=1", // 分享链接
            imgUrl: img,
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        wx.onMenuShareTimeline({
            title: "{$card['share_title']}", // 分享标题
            desc: "{$card['share_desc']}",
            imgUrl: img,
            link: location.protocol + "//" + window.location.hostname + "/Wap/Card/mobile?id={$card['card_id']}&reg_id={$reg['reg_id']}&share=1", // 分享链接
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
    })


</script>
<script src="/Public/js/common/baidutongji.js"></script>
</body>
</html>